﻿using System;
using System.Web;
using System.Data;
using System.Web.Mvc;
using System.Collections.Generic;
using System.Linq;
using BrnMall.Core;
using BrnMall.Services;
using BrnMall.Web.Framework;
using BrnMall.Web.StoreAdmin.Models;

namespace BrnMall.Web.StoreAdmin.Controllers
{
    /// <summary>
    /// 商城后台用户控制器类
    /// </summary>
    public partial class UserController : BaseStoreAdminController
    {
        /// <summary>
        /// 用户列表
        /// </summary>
        public ActionResult List(string nickName, string userName, string email, string mobile, int userRid = 0, int mallAGid = 0, int pageNumber = 1, int pageSize = 15)
        {
            var condition = Users.GetUserListCondition(nickName, userName, email, mobile,WorkContext.StoreId, userRid);

            var pageModel = new PageModel(pageSize, pageNumber, Users.GetUserCount(condition));
            
            var userRankList =
                new List<SelectListItem> {new SelectListItem() {Text = "全部等级", Value = "0"}};
            userRankList.AddRange(UserRanks.GetStoreUserRankList(WorkContext.StoreId).Select(info => new SelectListItem() {Text = info.Title, Value = info.UserRid.ToString()}));

            var model = new UserListModel()
            {
                PageModel = pageModel,
                UserList = Users.GetUserList(pageModel.PageSize, pageModel.PageNumber, condition),
                UserName = userName,
                Email = email,
                Mobile = mobile,
                UserRid = userRid,
                UserRankList = userRankList,
                MallAGid = mallAGid,
                NickName = nickName
            };

            MallUtils.SetAdminRefererCookie(
                $"{Url.Action("list")}?pageNumber={pageModel.PageNumber}&pageSize={pageModel.PageSize}&userName={userName}&email={email}&mobile={mobile}&userRid={userRid}&mallAGid={mallAGid}&nickname={nickName}");
            return View(model);
        }
        /// <summary>
        /// 编辑用户
        /// </summary>
        [HttpGet]
        public ActionResult Edit(int uid = -1)
        {
            UserInfo userInfo = Users.GetUserById(uid);
            if (userInfo == null)
                return PromptView("用户不存在");

            UserModel model = new UserModel
            {
                UserName = userInfo.UserName,
                Email = userInfo.Email,
                Mobile = userInfo.Mobile,
                UserRid = userInfo.UserRid,
                MallAGid = userInfo.MallAGid,
                NickName = userInfo.NickName,
                Avatar = userInfo.Avatar,
                PayCredits = userInfo.PayCredits,
                Gender = userInfo.Gender,
                RealName = userInfo.RealName,
                Bday = userInfo.Bday,
                IdCard = userInfo.IdCard,
                RegionId = userInfo.RegionId,
                Address = userInfo.Address,
                Bio = userInfo.Bio,
                Company = userInfo.Company,
                JobTitle = userInfo.JobTitle
            };

            Load(model.RegionId);

            //会员余额、充值总额、支出总额
            var cashRecord = Manager.Manager.User.CashRecordManager.GetTotalMoney(WorkContext.StoreId, userInfo.Uid);
            var userCash = Manager.Manager.User.UserCashManager.GetInfo(userInfo.Uid);
            model.InMoney = cashRecord["TimeInMoney"];
            model.OutMoney = cashRecord["TimeOutMoney"];
            model.UserCash = userCash == null ? 0 : BrnMall.Services.CashOrders.DecodeCash(userCash.Cash);
            return View(model);
        }

        /// <summary>
        /// 编辑用户
        /// </summary>
        [HttpPost]
        public ActionResult Edit(UserModel model, int uid = -1)
        {
            
            UserInfo userInfo = Users.GetUserById(uid);
            if (userInfo == null)
                return PromptView("用户不存在");

            int uid2 = Users.GetUidByUserName(model.UserName);
            if (uid2 > 0 && uid2 != uid)
                ModelState.AddModelError("UserName", "用户名已经存在");

            int uid3 = Users.GetUidByEmail(model.Email);
            if (uid3 > 0 && uid3 != uid)
                ModelState.AddModelError("Email", "邮箱已经存在");

            int uid4 = Users.GetUidByMobile(model.Mobile);
            if (uid4 > 0 && uid4 != uid)
                ModelState.AddModelError("Mobile", "手机号已经存在");

            if (ModelState.IsValid)
            {
                string nickName;
                if (string.IsNullOrWhiteSpace(model.NickName))
                    nickName = userInfo.NickName;
                else
                    nickName = model.NickName;

                userInfo.UserName = model.UserName;
                userInfo.Email = model.Email ?? "";
                userInfo.Mobile = model.Mobile ?? "";
                if (!string.IsNullOrWhiteSpace(model.Password))
                    userInfo.Password = Users.CreateUserPassword(model.Password, userInfo.Salt);
                if (userInfo.UserRid != model.UserRid)
                {
                    userInfo.UserRid = model.UserRid;
                    userInfo.RankCredits = UserRanks.GetUserRankById(model.UserRid).CreditsLower;
                }
                userInfo.MallAGid = model.MallAGid;
                userInfo.NickName = WebHelper.HtmlEncode(nickName);
                userInfo.Avatar = model.Avatar == null ? userInfo.Avatar : WebHelper.HtmlEncode(model.Avatar);
                userInfo.PayCredits = model.PayCredits;
                var rankInfo = UserRanks.GetUserRankById(model.UserRid);
                userInfo.LiftBanTime = rankInfo!=null ? DateTime.Now.AddDays(rankInfo.LimitDays) : new DateTime(1900, 1, 1);
                userInfo.Gender = model.Gender;
                userInfo.RealName = model.RealName == null ? "" : WebHelper.HtmlEncode(model.RealName);
                userInfo.Bday = model.Bday ?? new DateTime(1970, 1, 1);
                userInfo.IdCard = model.IdCard ?? "";
                userInfo.RegionId = model.RegionId;
                userInfo.Address = model.Address == null ? "" : WebHelper.HtmlEncode(model.Address);
                userInfo.Bio = model.Bio == null ? "" : WebHelper.HtmlEncode(model.Bio);
                userInfo.Company = model.Company ?? "";
                userInfo.JobTitle = model.JobTitle ?? "";
                Users.UpdateUser(userInfo);
                AddStoreAdminLog("修改用户", "修改用户,用户ID为:" + uid);
                return PromptView("用户修改成功");
            }

            Load(model.RegionId);

            return View(model);
        }
        private void Load(int regionId)
        {
            List<SelectListItem> userRankList = new List<SelectListItem>();
            userRankList.Add(new SelectListItem() { Text = "选择会员等级", Value = "0" });
            foreach (UserRankInfo info in UserRanks.GetStoreUserRankList(WorkContext.StoreId))
            {
                userRankList.Add(new SelectListItem() { Text = info.Title, Value = info.UserRid.ToString() });
            }
            ViewData["userRankList"] = userRankList;



            List<SelectListItem> mallAdminGroupList = new List<SelectListItem>();
            mallAdminGroupList.Add(new SelectListItem() { Text = "选择管理员组", Value = "0" });
            foreach (MallAdminGroupInfo info in MallAdminGroups.GetMallAdminGroupList())
            {
                if (info.MallAGid == 1)
                    mallAdminGroupList.Add(new SelectListItem() { Text = info.Title, Value = info.MallAGid.ToString() });
            }
            foreach (MallAdminGroupInfo info in MallAdminGroups.GetCustomerStoreAdminGroupList(WorkContext.StoreId))
            {
                mallAdminGroupList.Add(new SelectListItem() { Text = info.Title, Value = info.MallAGid.ToString() });
            }
            ViewData["AdminGroupList"] = mallAdminGroupList;
            RegionInfo regionInfo = Regions.GetRegionById(regionId);
            if (regionInfo != null)
            {
                ViewData["provinceId"] = regionInfo.ProvinceId;
                ViewData["cityId"] = regionInfo.CityId;
                ViewData["countyId"] = regionInfo.RegionId;
            }
            else
            {
                ViewData["provinceId"] = -1;
                ViewData["cityId"] = -1;
                ViewData["countyId"] = -1;
            }

            ViewData["referer"] = MallUtils.GetMallAdminRefererCookie();
        }
    }
}
